import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '../../store';
import { Checkbox, Stepper, SubmitBar, Dialog } from 'react-vant'
import { useNavigate } from 'react-router-dom';

const Index: React.FC = () => {
  // 1. 获取数据
  const cartList = useSelector((state: RootState) => state.car.cartList);
  // 2. 全选状态
  //       所有数据状态为真     => 全选状态为真
  //       存在任意数据状态为假     => 全选状态为假
  const allState = cartList.every(v => v.state)
  // 3. 总价
  const allPrice = cartList.filter(v => v.state).reduce((p, n) => {
    return p + n.price * n.count
  }, 0)
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const onSubmit = () => {
    navigate('/order', {
      state: {
        title: '商品标题',
        price: allPrice,
        id: new Date().getTime()
      }
    })
  }
  return (
    <div className='cart'>
      {
        cartList.map((v, i) => {
          return <dl key={i}>
            <dd>
              <Checkbox checked={v.state} onChange={() => dispatch({ type: 'oneState', payload: v })}></Checkbox>
            </dd>
            <dt>
              <img src={v.image} alt="" />
            </dt>
            <dd>
              <h3>{v.title}</h3>
              <Stepper
                value={v.count}
                min={1}
                onPlus={() => dispatch({ type: 'addCar', payload: v })}
                onMinus={() => dispatch({ type: 'subCar', payload: v })}
                onOverlimit={
                  () => Dialog.confirm({
                    title: '警告',
                    message: '在减少就要删除了'
                  })
                    .then(() => {
                      dispatch({ type: 'delCar', payload: v })
                    })
                    .catch(() => { })
                }
              ></Stepper>
              <p>单价：{v.price}</p>
            </dd>
          </dl>
        })
      }

      <SubmitBar
        price={allPrice * 100}
        buttonText="提交订单"
        onSubmit={() => onSubmit()}
      >
        <Checkbox checked={allState} onChange={() => dispatch({ type: 'allState', payload: !allState })}>全选</Checkbox>
      </SubmitBar>
    </div>
  )
}

export default Index